package com.szgd.controller.personnel;

import com.szgd.bean.Health;
import com.szgd.bean.SysDict;
import com.szgd.controller.BaseController;
import com.szgd.service.personnel.PersonnelInfoService;
import com.szgd.service.personnel.TrainService;
import com.szgd.service.sys.SysDictService;
import com.szgd.util.Constant;
import com.szgd.util.ExcelUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.TimeUtil;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping(value = "/train")
public class TrainController extends BaseController {
    private static Logger logger = Logger.getLogger(TrainController.class);

    @Autowired
    TrainService trainService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    PersonnelInfoService personnelInfoService;

    @RequestMapping(value = "toTrainList", method = RequestMethod.GET)
    public String toTrainList() {
        return "/personnel/train/trainList";
    }

    @RequestMapping(value = "/getTrainList", method = RequestMethod.GET)
    public void  getTrainList(HttpServletResponse response,HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        List<Map<String, Object>> dataList = trainService.getTrainList(paramMap);
        outTableJSONDataCommon(response, dataList);
    }

    @RequestMapping(value = "/trainDetail", method = RequestMethod.GET)
    public ModelAndView trainDetail(
            @RequestParam("id") long id,
            @RequestParam("status") int status,
            ModelAndView modelAndView
    ) throws UnsupportedEncodingException {
        Map<String,Object> trainInfo = trainService.getTrainDetailInfo(id);
        List<SysDict> workTypeList = sysDictService.getByParentCode("WORK_TYPE");
        List<SysDict> scoreTypeList = sysDictService.getByParentCode("SCORE_TYPE");
        List<SysDict> categoryList = sysDictService.getByParentCode("TRAIN_CATEGORY");
        modelAndView.setViewName("personnel/train/trainDetailInfo");
        modelAndView.addObject("id", id);
        modelAndView.addObject("status", status);
        modelAndView.addObject("train", trainInfo);
        modelAndView.addObject("workTypeList", workTypeList);
        modelAndView.addObject("scoreTypeList", scoreTypeList);
        modelAndView.addObject("categoryList", categoryList);
        return modelAndView;
    }

    @RequestMapping(value = "/saveTrainInfo")
    @ResponseBody
    public Map<String,Object> saveTrainInfo(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String, Object>> trainInfoList = trainService.getTrainListNoPage(paramMap);
            if(trainInfoList != null && trainInfoList.size() > 0){
                logger.error("保存失败：数据库已存在该员工培训，请勿重复添加");
                return getErrorMap("保存失败：数据库已存在该员工培训，请勿重复添加");
            }
            paramMap.put("uploader", this.getLoginId(request.getSession()));
            trainService.saveTrainInfo(paramMap);

            return getSuccMap("保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存失败："+e.getMessage());
            return getSuccMap("保存失败："+e.getMessage());
        }
    }

    @RequestMapping("/deleteTrain")
    public void deleteTrain(HttpServletRequest  request, HttpServletResponse response){
        JSONObject json=getJson();
        json.put("success", true);
        json.put("message", "删除成功!");
        try{
            Map<String, Object> params = this.getMapParams(request);
            params.put("userId", this.getLoginId(request.getSession()));
            boolean mark=trainService.deleteTrain(params)>0 ? true : false;
            if(!mark){
                json.put("message", "删除失败!");
            }
        }catch(Exception e){
            logger.error("删除失败！",e);
            json.put("message", "删除失败!");
        }
        outJSONData(response , json);
    }

    @RequestMapping(value = "/getTrainRecordList", method = RequestMethod.GET)
    public void  getTrainRecordList(HttpServletResponse response,HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        List<Map<String, Object>>  trainList = trainService.getTrainList(paramMap);
        if (trainList != null && trainList.size() > 0)
        {
            String beginTime = trainList.get(0).get("beginTime")==null?"":trainList.get(0).get("beginTime").toString();
            String endTime = trainList.get(0).get("endTime")==null?"":trainList.get(0).get("endTime").toString();
            if(beginTime.length() > 0){
                paramMap.put("beginTime",beginTime+" 00:00:01");
            }
            if(endTime.length() > 0){
                paramMap.put("endTime",endTime+" 23:59:59");
            }
            List<Map<String, Object>> dataList = trainService.getTrainRecordList(paramMap);
            outTableJSONDataCommon(response, dataList);
        }

    }

    @RequestMapping(value = "/toTrainAdd", method = RequestMethod.GET)
    public ModelAndView toTrainAdd(ModelAndView modelAndView) throws UnsupportedEncodingException {
        List<SysDict> categoryList = sysDictService.getByParentCode("TRAIN_CATEGORY");
        List<Map<String,Object>> personList = trainService.getAllPerson();
        modelAndView.addObject("categoryList", categoryList);
        modelAndView.addObject("personList", personList);
        modelAndView.setViewName("personnel/train/trainAdd");
        return modelAndView;
    }

    @RequestMapping(value = "/insertTrainInfo")
    @ResponseBody
    public Map<String,Object> insertTrainInfo(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        List<String> ids = new ArrayList<>();
        Object idObject = paramMap.get("PERSONNEL_ID");
        if (idObject != null)
        {
            if (idObject instanceof String) {
                ids.add(idObject.toString());
            } else if (idObject instanceof ArrayList) {
                ids = (ArrayList<String>) idObject;
            }
        }
        paramMap.put("creator",getLoginId(request.getSession()));
        String message = "";
        String msg = "";
        int flag = 0;
        try {
            List<String> names = new ArrayList<>();
            for(int i=0;i<ids.size();i++){
                Map<String, Object> personMap = new HashMap<>();
                personMap.put("id",ids.get(i));
                Map<String, Object> temp = personnelInfoService.getPersonnelInfo(personMap);
                String name = temp.get("name")==null?"":temp.get("name").toString();
                names.add(name);
                String inDate = temp.get("inDate")==null?"":temp.get("inDate").toString();
                String trainDate = paramMap.get("beginTime").toString();
                if(inDate.compareTo(trainDate) <=0){
                    message += temp.get("name")+",";
                    flag = 1;
                    continue;
                }
            }
            if(flag == 0){
                String err_name = "";
                for(int i=0;i<ids.size();i++) {
                    paramMap.put("personnelId", ids.get(i));
                    //判断是否已存在该培训记录
                    List<Map<String, Object>> trainInfoList = trainService.getTrainListNoPage(paramMap);
                    if(trainInfoList != null && trainInfoList.size() > 0){
                        err_name += names.get(i)+",";
                    }
                }
                if(err_name.length()==0){
                    for(int i=0;i<ids.size();i++) {
                        paramMap.put("personnelId", ids.get(i));
                        trainService.insertTrainInfo(paramMap);
                    }
                }else {
                    String err_msg = "培训信息新增失败："+err_name+"已参加该培训，请勿重复添加，请重新选择人员.";
                    logger.error(err_msg);
                    return getErrorMap(err_msg);
                }
            }
            if(message.length()==0){
                msg = "培训信息新增成功!";
            }else{
                msg = message+"因其培训日期在入场日期之后，故无法为上述人员添加该培训，请重新选择人员.";
            }
            return getSuccMap(msg);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("培训信息新增失败："+e.getMessage());
            return getSuccMap("培训信息新增失败："+e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/batchUploadTrain", method = {RequestMethod.GET, RequestMethod.POST})
    public void batchUploadTrain(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        long startTime = System.currentTimeMillis();
        InputStream in = null;
        List<List<Object>> listob = null;
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        in = file.getInputStream();
        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");  //防止ajax接受到的中文信息乱码
        response.setHeader("Content-type", "text/html;charset=UTF-8");   //跟上面同时使用可解决乱码问题
        out = response.getWriter();
        try {
            Map<String, String> fieldMapping = trainService.getFieldMap();
            List<Map<String, Object>> dataList = ExcelUtil.getListByExcel(in, file.getOriginalFilename(), fieldMapping, false);
            String batchNo = TimeUtil.formatDate(Calendar.getInstance().getTime(), "yyyyMMddhhmmss");
            Map<String, Object> resultMap = trainService.batchImportTrain(dataList, this.getLoginId(request.getSession()), batchNo);

            long endTime = System.currentTimeMillis();
            List<Map<String, Object>> successList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_SUCCESS);
            List<Map<String, Object>> ignoreList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_IGNORE);
            List<Map<String, Object>> failedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_FAILED);
            List<Map<String, Object>> updatedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_UPDATED);
            String errorHtml = failedList.size() + "条";

            if (failedList.size() > 0) {
                //生成失败记录文件
                String fileName = "培训列表" + batchNo + ".xls";
                String filePath = PropertiesUtil.get("batchImportErrorPath");
                String realPath = request.getServletContext().getRealPath(filePath);
                filePath = filePath.replace("\\", "/");
                File f = new File(realPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                realPath = realPath + File.separator + fileName;
                exportExcelByTemplate(fieldMapping,failedList, realPath,"培训信息批量导入模版.xls");
                String downloadPath = filePath + "/" + URLEncoder.encode(fileName,"UTF-8");
                errorHtml = "<a href='#WEBROOT#/downloadErrorRecord?path=" + downloadPath + "'>" + failedList.size() + "条（点击查看失败原因）</a>";
            }
            out.print("本次导入共处理" + dataList.size() + "条数据[新增：" + successList.size() + "条，更新："
                    + updatedList.size() + "条，<font color='red'>失败：" + errorHtml
                    + "</font>]，耗时： "
                    + (endTime - startTime) / 1000 + "秒！");
        } catch (Exception e) {
            out.print("文件导入失败！");
            logger.error(e.getMessage());
        }
        out.flush();
        out.close();
    }
}
